package cn.gok.springbootdemo06.logtest;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author: chen fan
 * @since: 2022/11/16 15:54
 * @description:
 */
@Controller
public class FileDownload {

    @RequestMapping("/fileDownload1")
    public ResponseEntity<byte[]> fileDownload1(String fileName) throws IOException {

        //读取文件
        BufferedInputStream bs = new BufferedInputStream(new FileInputStream("G:\\var\\log\\"+fileName));
        byte[] bytes = new byte[bs.available()];
        bs.read(bytes);

        //构建请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        //设置响应方式，以二进制流传输
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //告诉浏览器执行下载的操作，“attachment”告诉了浏览器进行下载,下载的文件文件名为 fileName
        httpHeaders.setContentDispositionFormData("attachment", fileName);

        return new ResponseEntity<byte[]>(bytes,httpHeaders, HttpStatus.CREATED);
    }


    /**
        借助IOUtils对象实现文件的下载
     */
    @RequestMapping("/fileDownload2")
    public void fileDownload2(String fileName, HttpServletResponse resp) throws IOException {

        //获取输入流： 先读取本地的文件
        FileInputStream fis = new FileInputStream("G:\\var\\log\\"+ fileName);

        //获取输出流，向前端发送数据
        ServletOutputStream os = resp.getOutputStream();

        //设置请求头
        resp.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));

        //输出
        IOUtils.copy(fis, os);

        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(os);
    }
}
